import { useEffect, useState } from "react";
import { List, Card, Button, Typography, Spin, message, Tabs, Badge } from "antd";
import { CheckCircleOutlined, CloudDownloadOutlined } from "@ant-design/icons";

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const VersionDownload = () => {
  const [remoteVersions, setRemoteVersions] = useState([]);
  const [localVersions, setLocalVersions] = useState([]);
  const [activeVersion, setActiveVersion] = useState(null);
  const [loadingRemote, setLoadingRemote] = useState(false);
  const [loadingLocal, setLoadingLocal] = useState(false);
  const [activeTab, setActiveTab] = useState("local");

  useEffect(() => {
    fetchRemoteReleases();
    fetchLocalVersions();
    loadActiveVersion(); // 加载已选择的版本
  }, []);

  // 从本地缓存加载已选择的版本
  const loadActiveVersion = () => {
    const savedVersion = localStorage.getItem('activeFrpVersion');
    if (savedVersion) {
      setActiveVersion(JSON.parse(savedVersion));
    }
  };

  // 获取远程版本
  const fetchRemoteReleases = async () => {
    setLoadingRemote(true);
    try {
      const res = await fetch("https://api.github.com/repos/fatedier/frp/releases");
      const data = await res.json();
      setRemoteVersions(data);
    } catch (err) {
      message.error("获取远程版本列表失败");
    } finally {
      setLoadingRemote(false);
    }
  };

  // 获取本地版本
  const fetchLocalVersions = async () => {
    setLoadingLocal(true);
    try {
      const res = await fetch("http://localhost:3001/api/local-versions");
      const data = await res.json();
      setLocalVersions(data);
    } catch (err) {
      message.error("获取本地版本列表失败");
    } finally {
      setLoadingLocal(false);
    }
  };

  // 获取Windows版本的下载链接
  const getAssetLink = (assets) => {
    const zip = assets.find(a => a.name.includes("windows") && a.name.endsWith(".zip"));
    return zip ? zip.browser_download_url : "";
  };

  // 处理使用版本
  const handleUseVersion = (versionInfo) => {
    // 保存版本信息到本地缓存
    localStorage.setItem('activeFrpVersion', JSON.stringify(versionInfo));
    setActiveVersion(versionInfo);

    const cached = localStorage.getItem('frp-global-config')
    const config = JSON.parse(cached) || {}
    config['frp_path'] = versionInfo.path
    localStorage.setItem('frp-global-config', JSON.stringify(config, null, 2))

    
    // 通知用户
    message.success(`已选择版本 ${versionInfo.version} (${versionInfo.arch})`);
    
    // 这里可以添加回调或事件，通知其他组件版本已变更
    window.dispatchEvent(new Event('versionChanged'));
  };

  // 检查是否为当前使用的版本
  const isActiveVersion = (versionInfo) => {
    return activeVersion && 
           activeVersion.name === versionInfo.name && 
           activeVersion.path === versionInfo.path;
  };

  return (
    <div style={{ maxHeight: "80vh", overflowY: "auto", paddingRight: 8 }}>
      <Title level={4}>FRP 版本管理</Title>
      
      {activeVersion && (
        <div style={{ marginBottom: 16, padding: 12, border: '1px solid #e8e8e8', borderRadius: 4, backgroundColor: '#fafafa' }}>
          <Text strong>当前使用版本:</Text> 
          <Text style={{ marginLeft: 8, color: '#1890ff' }}>
            {activeVersion.version} ({activeVersion.arch})
          </Text>
        </div>
      )}
      
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
      <TabPane 
          tab={
            <Badge count={localVersions.length}>
              <span>本地版本 <CheckCircleOutlined /></span>
            </Badge>
          } 
          key="local"
        >
          <Spin spinning={loadingLocal} tip="加载本地版本中...">
            <List
              grid={{ gutter: 16, column: 2 }}
              dataSource={localVersions}
              renderItem={(item) => (
                <List.Item>
                  <Card
                    title={`${item.version} (${item.arch})`}
                    extra={<Text type="secondary">{new Date(item.timestamp).toLocaleDateString()}</Text>}
                  >
                    <p style={{ height: 48, overflow: "hidden" }}>
                      <Text strong>路径:</Text> {item.path}
                    </p>
                    <Button
                      type={isActiveVersion(item)? "primary" : "default"}
                      icon={isActiveVersion(item)? <CheckCircleOutlined /> : null}
                      onClick={() => handleUseVersion(item)}
                    >
                      {isActiveVersion(item)? "正在使用" : "使用此版本"}
                    </Button>
                  </Card>
                </List.Item>
              )}
            />
          </Spin>
        </TabPane>
        <TabPane 
          tab={
            <Badge count={remoteVersions.length}>
              <span>远程版本 <CloudDownloadOutlined /></span>
            </Badge>
          } 
          key="remote"
        >
          <Spin spinning={loadingRemote} tip="加载远程版本中...">
            <List
              grid={{ gutter: 16, column: 2 }}
              dataSource={remoteVersions}
              renderItem={(item) => {
                const assetLink = getAssetLink(item.assets);
                const versionInfo = {
                  name: item.name,
                  version: item.tag_name,
                  arch: "amd64", // 假设远程版本默认为amd64
                  path: assetLink
                };
                
                return (
                  <List.Item>
                    <Card
                      title={item.name}
                      extra={<Text type="secondary">{new Date(item.published_at).toLocaleDateString()}</Text>}
                    >
                      <p style={{ height: 48, overflow: "hidden" }}>{item.body?.split("\n")[0]}</p>
                      <Button
                        type={isActiveVersion(versionInfo)? "primary" : "default"}
                        icon={isActiveVersion(versionInfo)? <CheckCircleOutlined /> : null}
                        disabled={!assetLink}
                        onClick={() => handleUseVersion(versionInfo)}
                      >
                        {isActiveVersion(versionInfo)? "正在使用" : "使用此版本"}
                      </Button>
                    </Card>
                  </List.Item>
                );
              }}
            />
          </Spin>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default VersionDownload;